package com.jk1.bianligou.blg.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jk1.bianligou.blg.common.ErrorCode;
import com.jk1.bianligou.blg.domain.dto.user.UserUpdateRequest;
import com.jk1.bianligou.blg.domain.po.User;
import com.jk1.bianligou.blg.exception.BizException;
import com.jk1.bianligou.blg.mapper.UserMapper;
import com.jk1.bianligou.blg.service.UserService;
import com.jk1.bianligou.blg.utils.PasswordUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.jk1.bianligou.blg.domain.constant.Constants.USER_ATTRIBUTE;


/**
 * @author WHH
 * @description 针对表【user(用户表)】的数据库操作Service实现
 * @createDate 2025-04-11 21:47:14
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {
    @Resource
    private UserMapper userMapper;

    @Override
    public User login(String username, String password, HttpServletRequest httpServletRequest) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        User user = userMapper.selectOne(wrapper);
        if (user != null && PasswordUtil.matches(password, user.getPassword())) {
            //设置为当前session的登录
            httpServletRequest.getSession().setAttribute(USER_ATTRIBUTE, user.getId());
            log.info("id :{}", httpServletRequest.getSession().getAttribute(USER_ATTRIBUTE));
            return user;
        }
        return null;
    }

    @Override
    public User getUserById(Long id) {
        return getById(id);
    }

    @Override
    public void updateUser(UserUpdateRequest request) {
        User user = new User();
        BeanUtil.copyProperties(request, user);
        boolean success = updateById(user);
        if (!success) {
            throw new BizException(ErrorCode.SYSTEM_ERROR);
        };
    }

    @Override
    public void deleteUser(Long id) {
        removeById(id);
    }

    @Override
    public boolean sign(Long id) {
        //签到逻辑
        return false;
    }

    @Override
    public Long userRegister(String userAccount, String userPassword, String ensurePassword) {
        //判空
        if (StrUtil.isAllBlank(userAccount, userPassword, ensurePassword)) {
            throw new BizException(ErrorCode.PARAMS_ERROR, "账号密码为空");
        }

        //账户长度不小于4位
        if (userAccount.length() < 4) {
            throw new BizException(ErrorCode.PARAMS_ERROR, "账户太短");
        }

        //密码不小于8位
        if (userPassword.length() < 8) {
            throw new BizException(ErrorCode.PARAMS_ERROR, "密码太短");
        }

        //账户不包含特殊字符
        String pattern = "[[ _`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]|\\n|\\r|\\t]+";
        Matcher matcher = Pattern.compile(pattern).matcher(userAccount);
        if (matcher.find()) {
            throw new BizException(ErrorCode.PARAMS_ERROR, "账号包含特殊字符");
        }

        //密码与确认密码相同
        if (!userPassword.equals(ensurePassword)) {
            throw new BizException(ErrorCode.PARAMS_ERROR, "两次密码输入不相同");
        }

        //账户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userAccount);
        Long result = userMapper.selectCount(queryWrapper);
        if (result != 0) {
            throw new BizException(ErrorCode.PARAMS_ERROR, "账号重复");
        }

        //对密码加密
        String encryptedPassword = PasswordUtil.encrypt(userPassword);
        //存入数据库
        User insertUser = new User();
        insertUser.setUsername(userAccount);
        insertUser.setPassword(encryptedPassword);
        insertUser.setNickname(RandomUtil.randomString(10));
        boolean save = this.save(insertUser);
        if (!save) {
            throw new BizException(ErrorCode.PARAMS_ERROR, "保存失败");
        }
        return insertUser.getId();
    }
}




